package org.ngmj.client;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;
import org.ngmj.message.*;
import org.ngmj.protocol.MessageCodecSharable;
import org.ngmj.protocol.ProtocolFrameDecoder;

import java.util.Arrays;
import java.util.Scanner;
import java.util.Set;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Collectors;

@Slf4j
public class Client {
    public static void main(String[] args) {
        NioEventLoopGroup group = new NioEventLoopGroup();
        MessageCodecSharable codecSharable = new MessageCodecSharable();
        LoggingHandler loggingHandler = new LoggingHandler(LogLevel.DEBUG);
        try {
            CountDownLatch lock = new CountDownLatch(1);
            AtomicBoolean login = new AtomicBoolean(false);
            ChannelFuture channelFuture = new Bootstrap()
                    .group(group)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<NioSocketChannel>() {
                        @Override
                        protected void initChannel(NioSocketChannel socketChannel) throws Exception {
                            socketChannel.pipeline()
                                    .addLast(new ProtocolFrameDecoder())
//                                    .addLast(loggingHandler)
                                    .addLast(codecSharable);
                            socketChannel.pipeline().addLast(new ChannelInboundHandlerAdapter() {

                                @Override
                                public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                                    log.info("msg:{}", msg);
                                    if (msg instanceof LoginResponseMessage responseMessage) {
                                        if (responseMessage.isSuccess()) {
                                            login.set(true);
                                        } else {
                                            login.set(false);
                                            log.debug("登录失败");
                                        }
                                        lock.countDown();
                                    }
                                }

                                @Override
                                public void channelActive(ChannelHandlerContext ctx) throws Exception {
                                    log.debug("connected...");
                                    new Thread(() -> {
                                        Scanner scanner = new Scanner(System.in);
                                        System.out.println("请输入用户名：");
                                        String username = scanner.nextLine();
                                        System.out.println("请输入密码：");
                                        String password = scanner.nextLine();
                                        LoginRequestMessage loginRequestMessage = new LoginRequestMessage(username, password);
                                        ctx.writeAndFlush(loginRequestMessage);
                                        try {
                                            lock.await();
                                            if (login.get()){
                                                while (true){
                                                    while (true) {
                                                        System.out.println("==================================");
                                                        System.out.println("send [username] [content]");
                                                        System.out.println("gsend [group name] [content]");
                                                        System.out.println("gcreate [group name] [m1,m2,m3...]");
                                                        System.out.println("gmembers [group name]");
                                                        System.out.println("gjoin [group name]");
                                                        System.out.println("gquit [group name]");
                                                        System.out.println("quit");
                                                        System.out.println("==================================");
                                                        String command = scanner.nextLine();
                                                        if (command != null && !command.isEmpty()) {
                                                            String[] commandList = command.split(" ");
                                                            switch (commandList[0]) {
                                                                case "send":
                                                                    ChatRequestMessage message = new ChatRequestMessage(username, commandList[1], commandList[2]);
                                                                    ctx.channel().writeAndFlush(message);
                                                                    break;
                                                                case "gsend":
                                                                    GroupChatRequestMessage groupMessage = new GroupChatRequestMessage(username, commandList[1], commandList[2]);
                                                                    ctx.channel().writeAndFlush(groupMessage);
                                                                    break;
                                                                case "gcreate":
                                                                    String members = commandList[2];
                                                                    if (members != null && !members.isEmpty()) {
                                                                        String[] memberList = members.split(",");
                                                                        Set<String> memberSet = Arrays.stream(memberList).collect(Collectors.toSet());
                                                                        GroupCreateRequestMessage groupCreateRequestMessage = new GroupCreateRequestMessage(commandList[1], memberSet);
                                                                        ctx.channel().writeAndFlush(groupCreateRequestMessage);
                                                                    }
                                                                    break;
                                                                case "gmembers":
                                                                    GroupMembersRequestMessage groupMembersRequestMessage = new GroupMembersRequestMessage(commandList[1]);
                                                                    ctx.channel().writeAndFlush(groupMembersRequestMessage);
                                                                    break;
                                                                case "gjoin":
                                                                    GroupJoinRequestMessage groupJoinRequestMessage = new GroupJoinRequestMessage(username, commandList[1]);
                                                                    ctx.channel().writeAndFlush(groupJoinRequestMessage);
                                                                    break;
                                                                case "gquit":
                                                                    GroupQuitRequestMessage groupQuitRequestMessage = new GroupQuitRequestMessage(username, commandList[1]);
                                                                    ctx.channel().writeAndFlush(groupQuitRequestMessage);
                                                                    break;
                                                                case "quit":
                                                                    ctx.channel().close();
                                                                    return;
                                                            }
                                                        }
                                                    }
                                                }
                                            }else {
                                                ctx.channel().close();
                                            }
                                        } catch (InterruptedException e) {
                                            throw new RuntimeException(e);
                                        }
                                    }).start();
                                }
                            });
                        }
                    })
                    .connect("127.0.0.1", 8080);
            channelFuture.sync();
            channelFuture.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            log.error("", e);
            throw new RuntimeException(e);
        } finally {
            group.shutdownGracefully();
        }

    }
}
